import React, { useState } from 'react'
import { View, Text } from '@tarojs/components'
import { Button, Grid } from '@taroify/core'
import Taro, { useShareAppMessage, useShareTimeline } from '@tarojs/taro'
import './index.scss'

const Calculator = () => {
  const [display, setDisplay] = useState('0')
  const [firstOperand, setFirstOperand] = useState(null)
  const [operator, setOperator] = useState(null)
  const [waitingForSecondOperand, setWaitingForSecondOperand] = useState(false)
  const [calculationComplete, setCalculationComplete] = useState(false)
  const [expression, setExpression] = useState('')

  // 分享给朋友
  useShareAppMessage(() => {
    return {
      title: '发现一个超好用的计算器，颜值高功能强，告别计算烦恼！✨',
      path: '/pages/calculator/index',
      imageUrl: 'cloud://cloud1-1ghcuz1u4c694d57.636c-cloud1-1ghcuz1u4c694d57-1304750880/images/share-img.png' // 可以添加分享图片URL
    }
  })

  // 分享到朋友圈
  useShareTimeline(() => {
    return {
      title: '发现一个超好用的计算器，颜值高功能强，告别计算烦恼！✨',
      query: '',
      imageUrl: 'cloud://cloud1-1ghcuz1u4c694d57.636c-cloud1-1ghcuz1u4c694d57-1304750880/images/share-img.png' // 可以添加分享图片URL
    }
  })

  const handleBack = () => {
    Taro.navigateBack()
  }

  const clearDisplay = () => {
    setDisplay('0')
    setFirstOperand(null)
    setOperator(null)
    setWaitingForSecondOperand(false)
    setCalculationComplete(false)
    setExpression('')
  }

  const inputDigit = (digit) => {
    if (calculationComplete) {
      setDisplay(String(digit))
      setCalculationComplete(false)
      setExpression(String(digit))
      setFirstOperand(null)
      setOperator(null)
      return
    }

    if (waitingForSecondOperand) {
      setDisplay(String(digit))
      setWaitingForSecondOperand(false)
      setExpression(`${expression}${digit}`)
    } else {
      setDisplay(display === '0' ? String(digit) : display + digit)
      setExpression(display === '0' ? String(digit) : expression + digit)
    }
  }

  const inputDecimal = () => {
    if (waitingForSecondOperand) {
      setDisplay('0.')
      setWaitingForSecondOperand(false)
      setExpression(`${expression}0.`)
      return
    }

    if (!display.includes('.')) {
      setDisplay(display + '.')
      setExpression(expression + '.')
    }
  }

  const handleOperator = (nextOperator) => {
    const inputValue = parseFloat(display)
    const operatorDisplay = getOperatorDisplay(nextOperator)

    if (calculationComplete) {
      setFirstOperand(inputValue)
      setExpression(`${inputValue} ${operatorDisplay} `)
      setCalculationComplete(false)
    } else if (firstOperand === null) {
      setFirstOperand(inputValue)
      setExpression(`${inputValue} ${operatorDisplay} `)
    } else if (operator) {
      const result = calculate(firstOperand, inputValue, operator)
      setDisplay(String(result))
      setFirstOperand(result)
      setExpression(`${result} ${operatorDisplay} `)
    }

    setWaitingForSecondOperand(true)
    setOperator(nextOperator)
  }

  const getOperatorDisplay = (op) => {
    switch (op) {
      case '+':
        return '+'
      case '-':
        return '-'
      case '*':
        return '×'
      case '/':
        return '÷'
      default:
        return op
    }
  }

  const calculate = (firstOp, secondOperand, op) => {
    switch (op) {
      case '+':
        return firstOp + secondOperand
      case '-':
        return firstOp - secondOperand
      case '*':
        return firstOp * secondOperand
      case '/':
        return firstOp / secondOperand
      default:
        return secondOperand
    }
  }

  const handleEquals = () => {
    if (!operator || firstOperand === null) return

    const inputValue = parseFloat(display)
    const result = calculate(firstOperand, inputValue, operator)
    const operatorDisplay = getOperatorDisplay(operator)

    setDisplay(String(result))
    setFirstOperand(result)
    setOperator(null)
    setWaitingForSecondOperand(false)
    setCalculationComplete(true)
    setExpression(`${firstOperand} ${operatorDisplay} ${inputValue} = ${result}`)
  }

  const toggleSign = () => {
    const value = -1 * parseFloat(display)
    setDisplay(String(value))
    if (waitingForSecondOperand) {
      setExpression(`${firstOperand} ${getOperatorDisplay(operator)} ${value}`)
    } else {
      setExpression(String(value))
    }
  }

  const calculatePercentage = () => {
    const inputValue = parseFloat(display)
    const result = inputValue / 100
    setDisplay(String(result))
    if (waitingForSecondOperand) {
      setExpression(`${firstOperand} ${getOperatorDisplay(operator)} ${result}`)
    } else {
      setExpression(String(result))
    }
  }

  return (
    <View className='calculator-page'>
      <View className='calculator'>
        <View className='display'>
          <Text className='expression-text'>{expression}</Text>
          <Text className='display-text'>{display}</Text>
        </View>

        <Grid columns={4} gutter={2} className='keypad'>
          <Grid.Item>
            <Button className='key function-key' onClick={clearDisplay}>
              AC
            </Button>
          </Grid.Item>
          <Grid.Item>
            <Button className='key function-key' onClick={toggleSign}>
              +/-
            </Button>
          </Grid.Item>
          <Grid.Item>
            <Button className='key function-key' onClick={calculatePercentage}>
              %
            </Button>
          </Grid.Item>
          <Grid.Item>
            <Button className='key operator-key' onClick={() => handleOperator('/')}>
              ÷
            </Button>
          </Grid.Item>

          <Grid.Item>
            <Button className='key number-key' onClick={() => inputDigit(7)}>
              7
            </Button>
          </Grid.Item>
          <Grid.Item>
            <Button className='key number-key' onClick={() => inputDigit(8)}>
              8
            </Button>
          </Grid.Item>
          <Grid.Item>
            <Button className='key number-key' onClick={() => inputDigit(9)}>
              9
            </Button>
          </Grid.Item>
          <Grid.Item>
            <Button className='key operator-key' onClick={() => handleOperator('*')}>
              ×
            </Button>
          </Grid.Item>

          <Grid.Item>
            <Button className='key number-key' onClick={() => inputDigit(4)}>
              4
            </Button>
          </Grid.Item>
          <Grid.Item>
            <Button className='key number-key' onClick={() => inputDigit(5)}>
              5
            </Button>
          </Grid.Item>
          <Grid.Item>
            <Button className='key number-key' onClick={() => inputDigit(6)}>
              6
            </Button>
          </Grid.Item>
          <Grid.Item>
            <Button className='key operator-key' onClick={() => handleOperator('-')}>
              -
            </Button>
          </Grid.Item>

          <Grid.Item>
            <Button className='key number-key' onClick={() => inputDigit(1)}>
              1
            </Button>
          </Grid.Item>
          <Grid.Item>
            <Button className='key number-key' onClick={() => inputDigit(2)}>
              2
            </Button>
          </Grid.Item>
          <Grid.Item>
            <Button className='key number-key' onClick={() => inputDigit(3)}>
              3
            </Button>
          </Grid.Item>
          <Grid.Item>
            <Button className='key operator-key' onClick={() => handleOperator('+')}>
              +
            </Button>
          </Grid.Item>

          <Grid.Item span={2}>
            <Button className='key number-key zero' onClick={() => inputDigit(0)}>
              0
            </Button>
          </Grid.Item>
          <Grid.Item>
            <Button className='key number-key' onClick={inputDecimal}>
              .
            </Button>
          </Grid.Item>
          <Grid.Item>
            <Button className='key equals-key' onClick={handleEquals}>
              =
            </Button>
          </Grid.Item>
        </Grid>
      </View>
    </View>
  )
}

export default Calculator
